package com.cpr.ams.web.controller;

import com.cpr.ams.bean.BaseRole;
import com.cpr.ams.bean.extend.BaseRoleExtend;
import com.cpr.ams.exception.AmsException;
import com.cpr.ams.service.IBaseRoleService;
import com.cpr.ams.util.Result;
import com.cpr.ams.util.StatusCode;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 权限操作
 * @Author: GX Cui
 * @Date 3:39 下午 2021/4/12
 */
@Api(value = "角色管理管理",tags = {"角色管理接口"})
@Validated
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IBaseRoleService baseRoleService;

    @ApiOperation(value = "查询所有")
    @GetMapping(value = "findAll")
    public Result findAll(){
        List<BaseRole> list = baseRoleService.findAll();
        return Result.success(list);
    }

    @ApiOperation(value = "查询所有",notes = "级联权限")
    @GetMapping(value = "cascadePrivilegeFindAll")
    public Result cascadePrivilegeFindAll(){
        List<BaseRoleExtend> list = baseRoleService.cascadePrivilegeFindAll();
        return Result.success(list);
    }


    @ApiOperation(value = "通过id删除")
    @GetMapping(value = "deleteById")
    public Result deleteById(int id){
        try {
            baseRoleService.deleteById(id);
            return Result.success("删除成功");
        }catch (AmsException e){
            return Result.fail(StatusCode.ROLE_NOT_EXIST);
        }

    }

    @ApiOperation(value ="保存或更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "name", value = "角色名称",paramType = "query",required = true)
    })
    @PostMapping(value = "saveOrUpdate")
    public Result saveOrUpdate(Integer id,
                               @NotNull String name){
        BaseRole role = new BaseRole();
        role.setId(id);
        role.setName(name);
        int i = baseRoleService.saveOrUpdate(role);
        return Result.success(i);
    }

    @ApiOperation(value = "为角色授权")
    @PostMapping(value = "authorization")
    public Result authorization(int id,Integer[] privileges){
        List<Integer> ids = Arrays.asList(privileges);
        baseRoleService.authorization(id,ids);
        return Result.success("授权成功");
    }

}
